package com.dk.service.impl;

import com.dk.mapper.PermiRoleMapper;
import com.dk.mapper.RRoleMapper;
import com.dk.pojo.PermiRole;
import com.dk.pojo.PermiRoleExample;
import com.dk.pojo.RRole;
import com.dk.pojo.RRoleExample;
import com.dk.service.RRoleServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RRoleServiceImpl implements RRoleServiceI {

    //角色
    @Autowired
    private RRoleMapper rRoleMapper;

    //角色权限表
    @Autowired
    private PermiRoleMapper permiRoleMapper;

    @Override
    public List<RRole> getInfoServer() {
        return rRoleMapper.selectByExample(new RRoleExample());
    }


    @Override
    public void saveById(String rname, Integer[] nodeIds) {
        RRole rRole = new RRole();
        rRole.setRname(rname);
        //增加并返回ID 这个int i  不是返回的id 而是增加成功的次数
        int i = rRoleMapper.saveById(rRole);

        List<PermiRole> permiRoles = new ArrayList<>();
        for (Integer pid : nodeIds){
            PermiRole permiRole = new PermiRole();
            permiRole.setPid(pid);
            permiRole.setRid(rRole.getRid());
            permiRoles.add(permiRole);
        }
        int j = permiRoleMapper.insertBatch(permiRoles);
    }

    @Override
    public RRole getById(Integer rid) {
        return rRoleMapper.selectByPrimaryKey(rid);
    }

    @Override
    public void updateById(RRole rRole, Integer[] nodeIds) {

        //修改角色
        rRoleMapper.updateByPrimaryKeySelective(rRole);

        //根据角色id 条件删除中间表
        PermiRoleExample example = new PermiRoleExample();
        PermiRoleExample.Criteria criteria = example.createCriteria();
        criteria.andRidEqualTo(rRole.getRid());
        permiRoleMapper.deleteByExample(example);

        //删除完 在增加
        List<PermiRole> permiRoles = new ArrayList<>();
        for (Integer pid : nodeIds){
            PermiRole permiRole = new PermiRole();
            permiRole.setPid(pid);
            permiRole.setRid(rRole.getRid());
            permiRoles.add(permiRole);
        }
        int j = permiRoleMapper.insertBatch(permiRoles);
    }

    @Override
    public void deleteById(Integer rid) {
        //根据角色id 删除对应的数据
        rRoleMapper.deleteByPrimaryKey(rid);

        //根据角色id 条件删除中间表
        PermiRoleExample example = new PermiRoleExample();
        PermiRoleExample.Criteria criteria = example.createCriteria();
        criteria.andRidEqualTo(rid);
        permiRoleMapper.deleteByExample(example);
    }


    @Override
    public List<RRole> getUserById(Integer uid) {
        return rRoleMapper.getUserById(uid);
    }
}
